package org.example.exampreparationtreasure.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.example.exampreparationtreasure.model.entity.IncorrectQuestionRecord;

@Mapper
public interface IncorrectQuestionRecordMapper extends BaseMapper<IncorrectQuestionRecord> {
    
    /**
     * 分页查询指定用户和分类下的错题记录
     * 
     * @param page 分页参数
     * @param userId 用户ID
     * @param categoryId 分类ID
     * @return 分页结果
     */
    @Select("SELECT * FROM incorrect_question_records " +
            "WHERE user_id = #{userId} AND category_id = #{categoryId} " +
            "ORDER BY last_mistake_time DESC")
    IPage<IncorrectQuestionRecord> selectIncorrectQuestionsByCategory(
            Page<IncorrectQuestionRecord> page, 
            @Param("userId") Long userId, 
            @Param("categoryId") Long categoryId);
    
    /**
     * 通过联表查询指定用户和分类下的错题记录（兜底方案）
     * 
     * @param page 分页参数
     * @param userId 用户ID
     * @param categoryId 分类ID
     * @return 分页结果
     */
    @Select("SELECT iqr.* FROM incorrect_question_records iqr " +
            "INNER JOIN questions q ON iqr.question_id = q.question_id " +
            "WHERE iqr.user_id = #{userId} AND q.category_id = #{categoryId} " +
            "ORDER BY iqr.last_mistake_time DESC")
    IPage<IncorrectQuestionRecord> selectIncorrectQuestionsByCategoryWithJoin(
            Page<IncorrectQuestionRecord> page, 
            @Param("userId") Long userId, 
            @Param("categoryId") Long categoryId);
    
    /**
     * 分页查询指定用户在指定分类及其子分类下的错题记录
     * 
     * @param page 分页参数
     * @param userId 用户ID
     * @param categoryIds 分类ID列表（包含父分类及其所有子分类）
     * @return 分页结果
     */
    @Select("<script>" +
            "SELECT * FROM incorrect_question_records " +
            "WHERE user_id = #{userId} " +
            "<if test='categoryIds != null and categoryIds.size() > 0'>" +
            "AND category_id IN " +
            "<foreach collection='categoryIds' item='categoryId' open='(' separator=',' close=')'>" +
            "#{categoryId}" +
            "</foreach>" +
            "</if>" +
            "ORDER BY last_mistake_time DESC" +
            "</script>")
    IPage<IncorrectQuestionRecord> selectIncorrectQuestionsByCategories(
            Page<IncorrectQuestionRecord> page, 
            @Param("userId") Long userId, 
            @Param("categoryIds") java.util.List<Long> categoryIds);
}
